package org.xiaov.extra.web.interceptor;

import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.xiaov.core.string.StringHelper;
import org.xiaov.execption.XiaovAuthException;
import org.xiaov.extra.jwt.JWTHelper;
import org.xiaov.http.HttpCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 关于token的认证
 * @author: xiaovcloud
 * @date: 2021/2/1 20:25
 * @version：1.0
 */
@Component
public class XiaovTokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(XiaovTokenInterceptor.class);
    private static final String DEFAULT_OPTIONS = "OPTIONS";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //跨域第一次请求请求
        if (DEFAULT_OPTIONS.equals(request.getMethod())) {
            response.setStatus(HttpCode.HTTP_OK.getValue());
            return true;
        }
        //获取token
        String token = request.getHeader("authorization");
        if (StringHelper.isEmpty(token)) {
            token = request.getParameter("authorization");
        }
        //验证token
        if (StringHelper.isEmpty(token)) {
            throw new XiaovAuthException(HttpCode.HTTP_FORBIDDEN.getValue(), "登录失效，请重新登录");
        }
        Claims claims = JWTHelper.parseToken(token);
        //如果有效，说明已经登录
        if (claims != null && JWTHelper.validateToken(token)) {
            log.info("验证token成功，登录的token为{}", token);
            return true;
        }
        throw new XiaovAuthException(HttpCode.HTTP_FORBIDDEN.getValue(), "登录失效，请重新登录");
    }
}
